<?php
/*========================================= JooSam =========================================/
/																							/
/	Extention:		JooSam																	/
/	Created by:		ScriptPlanet.eu															/
/	Site:			http://www.scriptplanet.eu												/
/	Email:			support@scriptplanet.eu													/
/	Support:		http://www.scriptplanet.eu/support										/
/	Copyright:		2011 (c) ScriptPlanet.eu												/
/	License:		CC BY-NC-ND 3.0 ~ http://creativecommons.org/licenses/by-nc-nd/3.0/		/
/	File Version:	0001																	/
/																							/
/========================================== JooSam ========================================*/
// Joomla Security
defined('_JEXEC') or die;

class jsamModules extends jsamMain{

	public function getInfo($caller){

		## Now Live mod
		if($caller == 'live'){
			return $this->nowLive();
		}

		## Timezone function
		if($caller == 'tzone'){
			return $this->timeZone();
		}

		## Top Request mod
		if($caller == 'reqtop'){
			return $this->topRequest();
		}

		## Last played mod
		if($caller == 'history'){
			return $this->history();
		}

		## queue mod
		if($caller == 'queue'){
			return $this->queue();
		}

		if($caller == 'jsonHistory'){
			return $this->lastPlayedMod();
		}

		## json Live
		if($caller == 'jsonLive'){
			return $this->modLive();
		}
		## json Live
		if($caller == 'songid'){
			return $this->modLiveSid();
		}

	}


	// Function Returns songID of last one in history - and tell is running yes/no
	protected function modLiveSid(){
		
		$conf = $this->settings();
		$jsamTZ = $conf['samsrvtzone'];
		$servTZ = date_default_timezone_get();
		if($servTZ != $jsamTZ){ date_default_timezone_set($jsamTZ); }
		$date = date('Y-m-d H:i:s');

		$sdb = new jsamSamdb();
		$query = "	SELECT songID, date_played, duration, artist, title, requestID
					FROM historylist
					ORDER BY ID DESC
					LIMIT 0, 1
				";
		if($sql = $sdb->query($query)){
			while($row = $sql->fetch_assoc()){
				$data[] = $row;
			} $sql->free();
			$sdb->close();
			if($data != ''){
				$song = $data[0];

				$id = $song['songID'];
				$played = $song['date_played'];
				$duration = $song['duration'];
				$artist = $song['artist'];
				$title = $song['title'];
				$reqID = $song['requestID'];
				$duration1 = $duration/1000;
				$duration2 = round($duration1);
				
				$start = strtotime($played);
				$end = mktime(date("H", $start), date("i", $start), date("s", $start)+$duration2, date("m", $start), date("d", $start), date("Y", $start));
				$end1 = date('Y-m-d H:i:s', $end);

				if($end1 > $date){
					$result = array(
								'state' => 'playing',
								'songid' => $id );
				}
				else{
					$result = array(
								'state' => 'offline',
								'songid' => $id );
				}
			}
			else{
				$result = array(
							'state' => 'nodata',
							'songid' => '' );
			}
		}
		else{
			$result = array(
						'state' => 'nodata',
						'songid' => '' );
		}
		return $result;
	}

	// Function Returns many data of last one in history - and tell is running yes/no
	protected function modLive(){
		
		$conf = $this->settings();
		$jsamTZ = $conf['samsrvtzone'];
		$imgwidth = $conf['imgwidth'].'px';
		$imgheight = $conf['imgheight'].'px';
		$servTZ = date_default_timezone_get();
		if($servTZ != $jsamTZ){ date_default_timezone_set($jsamTZ); }
		if($imgheight == 'px' or $imgheight == ''){	$imgheight = '50px'; }
		if($imgwidth == 'px' or $imgwidth == ''){ $imgwidth = '50px'; }
		$date = date('Y-m-d H:i:s');

		$sdb = new jsamSamdb();
		$query = "	SELECT songID, date_played, duration, artist, title, requestID
					FROM historylist
					ORDER BY ID DESC
					LIMIT 0, 1
				";
		if($sql = $sdb->query($query)){
			while($row = $sql->fetch_assoc()){
				$data[] = $row;
			} $sql->free();
			$sdb->close();
			if($data != ''){
				$song = $data[0];
				
				$id = $song['songID'];
				$played = $song['date_played'];
				$duration = $song['duration'];
				$artist = $song['artist'];
				$title = $song['title'];
				$reqID = $song['requestID'];
				$duration1 = $duration/1000;
				$duration2 = round($duration1);
				
				$start = strtotime($played);
				$end = mktime(date("H", $start), date("i", $start), date("s", $start)+$duration2, date("m", $start), date("d", $start), date("Y", $start));
				$end1 = date('Y-m-d H:i:s', $end);
				$dur_left = $end - strtotime($date);
				$lefth = date('H', $dur_left);
				$lefth = $lefth - 1;
				$leftm = date('i', $dur_left);
				$lefts = date('s', $dur_left);
				

				if($artist != ''){
					$artist = utf8_encode($artist);
					$lastfm = $this->nowLiveLFM($artist);
					$lfmError = $lastfm['error'];
					$lfmData = $lastfm['image'];
				}
				else{
					$artist = '';
					$lfmError = 'noartist';
					$lfmData = JText::_("COM_JOOSAM_COM_REQUEST_IMG_NO_ARTIST_LASTFM");
				}

				if($reqID > 0){
					$reqdata = $this->liveRequestMSG($reqID);
					$reqErr = $reqdata['error'];
					$reqName = $reqdata['name'];
					$reqMsg = $reqdata['msg'];
				}
				else{
					$reqErr = 'norequest';
					$reqName = '';
					$reqMsg = '';
				}

				if($reqName == ''){$reqName = JText::_('COM_JOOSAM_ANONYMOUS');}
				if($reqMsg == ''){$reqMsg = JText::_('COM_JOOSAM_NOMSG');}

				if($end1 > $date){
					$result = array(
								'state' => 'playing',
								'songid' => $id,
								'start' => $played,
								'duration' => $duration2,
								'hour_left' => $lefth,
								'min_left' => $leftm,
								'sec_left' => $lefts,
								'end' => $end1,
								'reqID' => $reqID,
								'reqErr' => $reqErr,
								'reqName' => $reqName,
								'reqMsg' => $reqMsg,
								'artist' => $artist,
								'title' => utf8_encode($title),
								'imgtype' => $lfmError,
								'imgdata' => $lfmData,
								'imgwidth' => $imgwidth,
								'imgheight' => $imgheight,
								'lang_artist' => JText::_('COM_JOOSAM_ARTIST'),
								'lang_title' => JText::_('COM_JOOSAM_TITLE')
								
								);
				}
				else{
					$result = array(
								'state' => 'offline',
								'songid' => $id,
								'start' => $played,
								'duration' => $duration2,
								'hour_left' => '',
								'min_left' => '',
								'sec_left' => '',
								'end' => $end1,
								'reqID' => $reqID,
								'reqErr' => $reqErr,
								'reqName' => $reqName,
								'reqMsg' => $reqMsg,
								'artist' => $artist,
								'title' => utf8_encode($title),
								'imgtype' => $lfmError,
								'imgdata' => $lfmData,
								'imgwidth' => $imgwidth,
								'imgheight' => $imgheight,
								'imgheight' => $imgheight,
								'lang_artist' => JText::_('COM_JOOSAM_ARTIST'),
								'lang_title' => JText::_('COM_JOOSAM_TITLE')
								);
				}
			}
			else{
				$result = array(
							'state' => 'empty',
							'songid' => '',
							'start' => '',
							'duration' => '',
							'hour_left' => '',
							'min_left' => '',
							'sec_left' => '',
							'end' => '',
							'reqID' => '',
							'reqErr' => '',
							'reqName' => '',
							'reqMsg' => '',
							'artist' => '',
							'title' => '',
							'imgtype' => '',
							'imgdata' => '',
							'imgwidth' => '',
							'imgheight' => '',
							'imgheight' => $imgheight,
							'lang_artist' => JText::_('COM_JOOSAM_ARTIST'),
							'lang_title' => JText::_('COM_JOOSAM_TITLE')
							);
			}
		}
		else{
			$result = array(
						'state' => 'error',
						'songid' => '',
						'start' => '',
						'duration' => '',
						'hour_left' => '',
						'min_left' => '',
						'sec_left' => '',
						'end' => '',
						'reqID' => '',
						'reqErr' => '',
						'reqName' => '',
						'reqMsg' => '',
						'artist' => '',
						'title' => '',
						'imgtype' => '',
						'imgdata' => '',
						'imgwidth' => '',
						'imgheight' => '',
						'imgheight' => $imgheight,
						'lang_artist' => JText::_('COM_JOOSAM_ARTIST'),
						'lang_title' => JText::_('COM_JOOSAM_TITLE')
						);
		}
		return $result;
	}

	protected function nowLiveLFM($artist){
		$conf = $this->settings();
		$ApiKey = $conf['imglastfmkey'];
		
		if($ApiKey != ''){
			$lastfm = array(
						'url' => 'http://ws.audioscrobbler.com/2.0/',
						'method' => 'artist.getinfo',
						'data' => 'artist='.urlencode($artist),
						'ApiKey' => $ApiKey
			);
			$url = $lastfm['url'].'?method='.$lastfm['method'].'&'.$lastfm['data'].'&api_key='.$lastfm['ApiKey'];
			
			if(function_exists('curl_init')){
				$srv = curl_init($url);
				curl_setopt($srv, CURLOPT_HEADER, false);
				curl_setopt($srv, CURLOPT_RETURNTRANSFER, true);
				$srvData = curl_exec($srv);
				curl_close($srv);
				if($srvData == ''){
					$error = 'connect';
					$image = JText::_("COM_JOOSAM_COM_REQUEST_IMG_ERROR_CONNECT_LASTFM");
				}
				else{
					$lastferrorcd = array();
					preg_match('/\d\d\d/', $srvData, $lastferrorcd);
					$lastferrorcd[] = 'placeholder';
					if($lastferrorcd[0] == 404){
						$error = 'last404';
						$image = JText::_("COM_JOOSAM_COM_REQUEST_IMG_LASTFM_404_BACK");
					}
					else{
						$xml = simplexml_load_string($srvData);
						$status = $xml->attributes()->status;
						if($status == 'ok'){
							$image = $xml->artist[0]->image[4];
							if($image == ''){$image = $xml->artist[0]->image[3];}
							if($image == ''){$image = $xml->artist[0]->image[2];}
							if($image == ''){$image = $xml->artist[0]->image[1];}
							if($image == ''){$image = 'noimage';}
							if($image == 'noimage'){
								$image = JText::_("COM_JOOSAM_COM_REQUEST_IMG_LASTFM_NO_IMAGE");
								$error = 'noimage';
							}
							else{
								$error = 'passed';
							}
						}
						else if($status == 'failed'){
							$error = 'lastfmerr';
							$image = $xml->error;
						}
						else{
							$error = 'changed';
							$image = 'Last FM Changed Service.';
						}
					}
				}
			}
			else{
				$error = 'nocurl';
				$image = JText::_("COM_JOOSAM_COM_REQUEST_IMG_LASTFM_NO_CURL");
			}
		}
		else{
			$error = 'noapikey';
			$image = JText::_("COM_JOOSAM_COM_REQUEST_IMG_NO_APIKEY");
		}

		$result = array(
					'error' => $error,
					'image' => $image
					);
		
		return $result;
	}

	// Thanks msg
	protected function liveRequestMSG($id){

		$data = '';
		$name = '';
		$msg = '';
		$state = 'nodata';
		$sdb = new jsamSamdb();
		$query = "	SELECT msg, name FROM requestlist WHERE ID = '".$id."'";
		
		if($sql = $sdb->query($query)){
			while($row = $sql->fetch_assoc()){
				$data[] = $row;
			} $sql->free();
			$sdb->close();
			if($data != ''){
				$req = $data[0];
				$name = $req['name'];
				$msg = $req['msg'];
				$state = 'passed';
			}
		}

		$result = array(
					'name' => $name,
					'msg' => $msg,
					'error' => $state
					);
		return $result;
	}

	protected function lastPlayedMod(){
		$conf = $this->settings();
		$req = $this->requestconf();
		$songtype = $req['songtyp'];
		$jsamTZ = $conf['samsrvtzone'];
		$imgwidth = $conf['imgwidth'].'px';
		$imgheight = $conf['imgheight'].'px';
		$servTZ = date_default_timezone_get();
		if($servTZ != $jsamTZ){ date_default_timezone_set($jsamTZ); }
		if($imgheight == 'px' or $imgheight == ''){	$imgheight = '50px'; }
		if($imgwidth == 'px' or $imgwidth == ''){ $imgwidth = '50px'; }
		$date = date('Y-m-d H:i:s');
		$result = '';
		$data = '';
		$sdb = new jsamSamdb();
		$query = "	SELECT songID, date_played, duration, artist, title
					FROM historylist
					WHERE songtype IN(".$songtype.")
					ORDER BY ID DESC
					LIMIT 0, 10
				";
		if($sql = $sdb->query($query)){
			while($row = $sql->fetch_assoc()){
				$data[] = $row;
			} $sql->free();
			$sdb->close();
			if($data != ''){
				$scount = count($data);
				$scount = $scount - 1;

				$c = 0;
				while($c <= $scount){

					$song = $data[$c];
					$id = $song['songID'];
					$played = $song['date_played'];
					$duration = $song['duration'];
					$artist = $song['artist'];
					$title = $song['title'];
					$duration1 = $duration/1000;
					$duration2 = round($duration1);
				
					$start = strtotime($played);
					$end = mktime(date("H", $start), date("i", $start), date("s", $start)+$duration2, date("m", $start), date("d", $start), date("Y", $start));
					$end1 = date('Y-m-d H:i:s', $end);

					if($end1 < $date or $c != 0){
						$row[] = array(
									'type' => 'passed',
									'songid' => $id,
									'played' => $played,
									'artist' => utf8_encode($artist),
									'title' => utf8_encode($title)
								);
					}
					$c = $c +1;
				}
				$rcount = count($row);
				if($rcount > 5){
					$i = 0;
					while($i < 5){
						$result[] = $row[$i];
						$i = $i+1;
					}
				}
				else{
					$result = $row;
				}
			}
		}

		if($result == ''){
			$result =	array(
							array(
								'type' => 'error',
								'songid' => '',
								'played' => '',
								'artist' => '',
								'title' => ''
							)
						);
		}
		return $result;
	}




	protected function timeZone(){
		$conf = $this->settings();
		$tzone = $conf['samsrvtzone'];
		return $tzone;
	}

	protected function history(){

		$conf = $this->settings();
		$tzone = $conf['samsrvtzone'];
		date_default_timezone_set($tzone);
		$time = strtotime('now');
		$data = '';
		## Get songtypes. Only songstypes that are clients cen request are visible ( he don't look to the category
		$req = $this->requestconf();
		$songtype = $req['songtyp'];

		## Build database work
		$sdb = new jsamSamdb();

		$query = "	SELECT date_played, duration, artist, title FROM historylist WHERE songtype IN (".$songtype.") ORDER BY ID DESC LIMIT 0, 6 ";
		
		if($sql = $sdb->query($query)){
			while($row = $sql->fetch_assoc()){
				$date = $row['date_played'];
				$artist = $row['artist'];
				$title = $row['title'];
				$duration = $row['duration'] / 1000;

				$mintime = strtotime($date) + $duration;

				if($mintime < $time){
					$data[] = $row;
				}
			} $sql->free();
			$sdb->close();
			if($data != ''){
				return $data;
			}
			else{
				return false;
			}
		}
		else{
			return false;
		}
	}

	protected function topRequest(){
		
		## Get songtypes. Only songstypes that are clients cen request are visible ( he don't look to the category
		$req = $this->requestconf();
		$songtype = $req['songtyp'];

		## Build database work
		$sdb = new jsamSamdb();

		$query = "	SELECT artist, title, count_requested
					FROM songlist
					WHERE songtype IN (".$songtype.")
					ORDER BY count_requested DESC, count_played DESC, artist DESC
					LIMIT 0, 5 ";
		
		if($sql = $sdb->query($query)){
			while($row = $sql->fetch_assoc()){
				$data[] = $row;
			} $sql->free();
			$sdb->close();
			if($data != ''){
				return $data;
			}
			else{
				return false;
			}
		}
		else{
			return false;
		}
	}

	protected function queue(){

		## Get songtypes. Only songstypes that are clients cen request are visible ( he don't look to the category
		$req = $this->requestconf();
		$songtype = $req['songtyp'];

		## Build database work
		$sdb = new jsamSamdb();
		$data = '';
		$query = "	SELECT S.artist, S.title
					FROM songlist S, queuelist Q
					WHERE S.ID = Q.songID
						AND S.songtype IN (".$songtype.")
					ORDER BY Q.ID ASC
					LIMIT 0, 5 ";
		
		if($sql = $sdb->query($query)){
			while($row = $sql->fetch_assoc()){
				$data[] = $row;
			} $sql->free();
			$sdb->close();
			if($data != ''){
				return $data;
			}
			else{
				return false;
			}
		}
		else{
			return false;
		}
	}
}